<template>
  <div>
    <el-dialog v-model="state.showDialog" destroy-on-close :title="title" draggable :close-on-click-modal="false"
      :close-on-press-escape="false" width="500px">
      <el-form ref="formRef" :model="form" size="default" label-width="80px">
        <el-row :gutter="35">
          <el-col v-if="(state.form?.id == undefined)" :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="工站代号" :rules="[{ required: true, message: '请输入工站代号', trigger: ['blur', 'change'] }]">
              <template #label>
                <div class="my-flex-y-center">
                  工站<el-tooltip effect="dark" placement="top" :hide-after=0>
                    <template #content>只能新增工站，删除请选择【操作】▷【更多】▷【解绑功能】</template>
                    <SvgIcon name="ele-InfoFilled" class="ml5" />
                  </el-tooltip>
                </div>
              </template>
              <el-tree-select v-model="form.workStationIds" :data="state.stationTreeData" node-key="id"
                :props="{ label: 'stationCode' }" render-after-expand fit-input-width clearable filterable collapse-tags
                collapse-tags-tooltip class="w100" :default-expanded-keys="state.expandRowKeys" multiple
                @current-change="onStationCurrentChange">
                <template #default="{ data }">
                  <span class="my-flex my-flex-between">
                    <span>{{ data.stationCode }}</span>
                    <span class="my-line-1 my-mlr-12" :title="data.lineName">
                      {{ data.lineName }}
                    </span>
                  </span>
                </template>
              </el-tree-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="IP地址" prop="ipAddress" :rules="[{ trigger: ['blur', 'change'] }]">
              <el-input v-model="form.ipAddress" placeholder="请输入IP地址" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="端口号" prop="port"
              :rules="[{ required: true, message: '请输入端口号', trigger: ['blur', 'change'] }]">
              <el-input type="number" v-model="form.port" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="机架ID" prop="rackId"
              :rules="[{ required: true, message: '请输入机架ID', trigger: ['blur', 'change'] }]">
              <el-input type="number" min="0" max="10" v-model="form.rackId" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="插槽ID" prop="slotId"
              :rules="[{ required: true, message: '请输入插槽ID', trigger: ['blur', 'change'] }]">
              <el-input type="number" min="0" max="10" v-model="form.slotId" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="排序" prop="sort"
              :rules="[{ required: false, message: '排序', trigger: ['blur', 'change'] }]">
              <el-input-number v-model="form.sort" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer my-flex my-flex-y-center my-flex-between">
          <div>
            <el-checkbox v-if="!(state.form?.id > 0)" v-model="state.contiAdd">连续新增</el-checkbox>
          </div>
          <div>
            <el-button @click="onCancel" size="default">取 消</el-button>
            <el-button type="primary" @click="onSure" size="default" :loading="state.sureLoading">确 定</el-button>
          </div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="industry/station-plc/form">
import { reactive, toRefs, getCurrentInstance, ref } from 'vue'
import { StationPlcGetListOutput, StationPlcAddInput, StationPlcUpdateInput, WorkStationGetListOutput } from '/@/api/industry/data-contracts'
import { verifyIPAddress } from '/@/utils/toolsValidate'
import { StationPlcApi } from '/@/api/industry/StationPlc'
import { WorkStationApi } from '/@/api/industry/WorkStation'
import { listToTree, treeToList } from '/@/utils/tree'
import eventBus from '/@/utils/mitt'
import { trimStart, replace, cloneDeep } from 'lodash-es'
import { WorkStationGetOutput } from '/@/api/industry/data-contracts'
defineProps({
  title: {
    type: String,
    default: '',
  },
})
const { proxy } = getCurrentInstance() as any
const formRef = ref()
const state = reactive({
  showDialog: false,
  sureLoading: false,
  form: {} as StationPlcAddInput & StationPlcUpdateInput,
  contiAdd: false,
  stationTreeData: [] as WorkStationGetListOutput[],
  expandRowKeys: [] as Number[]
})
const { form } = toRefs(state)

const getStations = async () => {
  const res = await new WorkStationApi().getList({})
  if (res?.success && res.data && res.data.length > 0) {
    state.stationTreeData = listToTree(res.data) as WorkStationGetListOutput[]
  } else {
    state.stationTreeData = []
  }
}

// 打开对话框
const open = async (row: any = {}) => {
  await getStations()
  state.expandRowKeys = treeToList(cloneDeep(state.stationTreeData))
    .filter((a: WorkStationGetListOutput) => a.id === 0)
    .map((a: WorkStationGetListOutput) => a.id) as number[]
  state.contiAdd = false
  const res = await new StationPlcApi().getStation({ id: row.PLCDeivceId }).catch(() => {
    proxy.$modal.closeLoading()
  })
  if (res?.success) {
    state.form = res.data as StationPlcAddInput & StationPlcUpdateInput
    if (row.id > 0) {
      state.form = row
      state.form.workStationIds = res.data?.workStationIds
    } else {
      state.form = { id: undefined, plcDeviceId: row.PLCDeivceId } as StationPlcAddInput & StationPlcUpdateInput
    }
  }
  state.showDialog = true
}
// 确定
const onSure = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    state.sureLoading = true
    let res = {} as any
    if (state.form.id != undefined && state.form.id > 0) {
      res = await new StationPlcApi().update(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    } else {
      res = await new StationPlcApi().add(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    }
    state.sureLoading = false

    if (res?.success) {
      if (state.contiAdd) {
        formRef.value!.resetFields()
      }
      eventBus.emit('refreshStationPlc')
      state.showDialog = state.contiAdd
    }
  })
}

const onStationFilterNode = (value: string, data: WorkStationGetOutput) => {
  if (!value) return true
  return data.stationCode?.indexOf(value) !== -1 || data?.lineName?.indexOf(value) !== -1
}

const onStationCurrentChange = (data: WorkStationGetListOutput) => {
  if (data) {
    if (!state.form.workStationId) {
      state.form.workStationId = data.id
    }
  }
}
// 取消
const onCancel = () => {
  state.showDialog = false
}
defineExpose({
  open,
})
</script>